<?php

namespace app\controllers\pay;

use app\commission\PayForFinish;
use app\controllers\Controller;
use app\models\pay\PayFor;
use app\models\system\SetPay;
use app\util\Debug;
use app\util\Request;

class ForController extends Controller
{
    public static function pay($sn, $user_id, $amount, $bank_number, $bank_nickname, $type = 2, $type_text = '')
    {
        /*
         * sn:
         * cash->sn
         * merchant_pay->sn
         *
         * type:
         * 1 => 提现
         * 2 => 付给商家
         */

        // save pay for record
        $model = new PayFor();
        $model->sn = $sn;
        $model->user_id = $user_id;
        $model->amount = $amount;
        $model->status = 0;
        $model->type = $type;
        $model->bank_number = $bank_number;
        $model->bank_nickname = $bank_nickname;
        $model->type = $type;
        $model->type_text = $type_text;
        $model->save();


        $set = SetPay::getLastOne();
        // $wx = SetWx::getLastOne(false);

        $params = [
            'userNo' => $set->mid,
            //  朝夕付：不限出款时间，使用“可取余额”，正常5分钟内到账，偶尔半小时也属于正常时间范围；
            'productCode' => 'BANK_PAY_DAILY_ORDER',
            'requestTime' => date('Y-m-d H:i:s'),
            'merchantOrderNo' => $sn,

            // 收款人卡号与姓名
            'receiverAccountNoEnc' => $bank_number,
            'receiverNameEnc' => $bank_nickname,

            'receiverAccountType' => 201,
            'paidAmount' => round($amount, 2),
            'currency' => 201,
            'isChecked' => 202,
            'paidDesc' => '提现',
            // 代付用途 => 消费款项
            'paidUse' => 211,
            'callbackUrl' => \Yii::$app->request->getHostInfo() . '/pay/for/callback'
        ];

        try {
            $sign = Sign::signature($params);
            $data = array_merge($params, ['hmac' => md5($sign . $set->secret)]);

            $url = 'https://www.joinpay.com/payment/pay/singlePay';// 这里要用json请求
            $response = Request::json($url, json_encode($data));

            $result = json_decode($response);

            // var_dump($response, $result);exit;

            // 汇聚成功受理请求后同步返回
            if ($result && $result->statusCode == 2001) {
                return true;
            } else {
                /**
                 * 产品未开通, 这里不会有返回
                 * 在callback里返回
                 */
                throw new \Exception('请求代付失败' . $response);
            }

        } catch (\Exception $e) {
            Debug::pay('for-fail', $e->getMessage());
        }
    }

    public function actionCallback()
    {
        $data = $this->post();
        $data = json_encode($data);

        $result = json_decode($data);
        $model = PayFor::findOne(['sn' => $result->merchantOrderNo]);

        if ($model && $result->status == 205 && $result->paidAmount == $model->amount) {

            $params = $this->post();
            $model->request_params = json_encode($params);

            $model->status = 1;
            $model->save();

            // pay for finish
            PayForFinish::forFinish($model);

            // 返回给支付公司
            return json_encode([
                'statusCode' => '2001',
                'message' => '成功'
            ]);
        } else {
            Debug::pay('for-callback-error', $data);
        }

    }
}